//
//  ViewController.swift
//  Concentration
//
//  Created by chensk on 2019/6/18.
//  Copyright © 2019 chensk. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var flipCountLabel: UILabel!
    
    @IBOutlet var cardBtns: [UIButton]!
    
    
    //第一种 使用lazy 但是不能使用didSet
    lazy var games :Concentration =    Concentration(numberOfPairsOfCards:  (cardBtns.count)/2);
    
    var flipCount: Int = 0{
        didSet{
            flipCountLabel.text = "flips:\(flipCount)";
        }
        
    };
    
    @IBAction func touchCard(_ sender: UIButton) {
        flipCount+=1;
        if let cardNumber = cardBtns.index(of: sender){
            games.chooseCard(at: cardNumber);
            updateViewFromModel();
        }else{
            print("不存在序号");
        }
    }
    func updateViewFromModel(){
        for index in  cardBtns.indices{
            let button = cardBtns[index];
            let card = games.cards[index];
            if card.isFaceUp{
                 print(emoji(for : card));
                button.setTitle(emoji(for : card), for: UIControl.State.normal)
                button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1);
            }else{
                button.setTitle("",for: UIControl.State.normal);
                button.backgroundColor = card.isMatched ? #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1):#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1);
            }
          
        }
        
    }
  
    var emojiChoices = ["🐰","🐭","🐷","🐲","🐍","🐎","🐑","🐒","🐔","🐶"];
    var emoji = [Int:String]();
    func  emoji(for card :Card)->String{
        if emoji[card.identifier] == nil,emojiChoices.count>0 {
            let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)));
            emoji[card.identifier] = emojiChoices.remove(at: randomIndex);
         
        }
       let emj =  emoji[card.identifier] ?? "无"
       
        return emj;
    }
}


